package util;

/**
 * @Project : AlgorithmLearning
 * @Package : Leetcode
 * @File : List.java
 * @Author : WangRuoyu
 * @Date 2023/11/19 21:36
 */

public class LinkList {

    /***
     * 创建链表
     * ***/
    public static ListNode createList(int[] nodes) {
        ListNode head = new ListNode(-1);
        ListNode p = head;
        for (int i = nodes.length - 1; i >= 0; i--) {
            ListNode s = new ListNode(nodes[i]);
            s.next = p.next;
            p.next = s;
        }
        return head.next;
    }

    /***
     * 输出链表
     * ***/
    public static void printList(ListNode head) {
        while (head != null) {
            System.out.print(head.val + " ");
            head = head.next;
        }
        System.out.println();
    }

    /***
     * 合并两个有序链表
     * ***/
    public static ListNode mergeTwoSortedList(ListNode list1, ListNode list2) {
        if (list1 == null) return list2;
        if (list2 == null) return list1;
        if (list1.val > list2.val) {
            ListNode tmp = list1;
            list1 = list2;
            list2 = tmp;
        }

        ListNode head = list1;

        while (list2 != null) {
            if (list1.next == null) {
                list1.next = list2;
                break;
            } else if (list1.next.val >= list2.val) {
                ListNode tmp = list2.next;
                list2.next = list1.next;
                list1.next = list2;
                list1 = list2;
                list2 = tmp;
            } else {
                list1 = list1.next;
            }
        }
        return head;
    }
}

